package main;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CheckType {
	
	public enum VariableType  {
		INT("-?[0-9]+","int"), 
		DOUBLE("-?([0-9])+((\\.)([0-9])+)?","double"), 
		STRING("\".*\"","String"), 
		BOOLEAN("true|false|"+DOUBLE.getRegex(),"boolean"), 
		CHAR("'.'","char");
		
		private String regex;
		private String name;
		
		VariableType (String regex, String name) {
			this.regex=regex;
			this.name=name;
		}
		
		public String getRegex() {
		       return this.regex;
		}
		public String getName() {
		       return this.name;
		}

	}
	public static final String FINAL="final";
	public static final String VOID="void";
	public static final String RETURN="return";
	public static final String IF="if";
	public static final String WHILE="while";
	
	public static boolean isValidVariableName (String text) {
		return text.matches("(^[a-zA-Z]\\w*)|(^_\\w+)");
	}
	public static boolean isValidMethodName (String text) {
		return text.matches("(^[a-zA-Z]\\w*)");
	}
	public static boolean isCommand (String text) {
		return text.matches(".*;$");
	}
	public static boolean isBlock (String text) {
		return text.matches(".*\\{$");
	}
	public static boolean isVariableType (String type) {
		boolean isValidType=false;
		for (VariableType v: VariableType.values()) {
			if (v.getName().equals(type))
				isValidType=true;
		}
		return isValidType;
	}
	public static boolean isMethodType (String type) {
		boolean isValidType=isVariableType(type);
		if (VOID.equals(type))
			isValidType=true;
		
		return isValidType;
	}
	
	public static String getmethodType (String method) throws compilationException {
		Pattern pattern = Pattern.compile("([a-zA-Z]\\w*)\\((.*)\\)");
		Matcher matcher = pattern.matcher(method);
		if (matcher.find()) {
			for (Method m: Sjavac.methods) {
				if (m.getName().equals(matcher.group(1))) {
					m.checkParamCorrectness (matcher.group(2));
					return m.getType();
				}
			}
			throw new compilationException("Error 6: Method dosen't exist");
		}
		
		throw new compilationException("Error 6: UnKnown command");

	}
	
	public static boolean isValueMuchType (String value, String type) throws compilationException {
		VariableType varType = VariableType.valueOf(type.toUpperCase());
		if (!value.matches(varType.getRegex())) {
			for (Variable v: Sjavac.members) {
				if (v.getName().equals(value)) {
					if(!(v.getType().equals(type) && v.getValue()))
					return false;
				}
			}
			
			if(!CheckType.getmethodType(value).equals(type))
				return false;	
		}
		return true;
		
	}
}
